﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;
using MFD.SharePoint.Notifications;

namespace MFD.SharePoint.TaskNotification
{
    /// <summary>
    /// We need to send 4 notifications
    /// 
    /// 1. Task about to start: Sent when there are just a few days(confgurable) till start date and the task is "Not Started"
    /// 2. Task not started: Sent when the start date in the past and task not Started
    /// 3. Task due in few days (configurable). Sent when the due date is approaching and the task is in progress
    /// 4. Task overdue: Sent when the due date is in the past and task is not Completed
    /// </summary>
    public class TaskNotification
    {
        public const string NOTIFICATION_SITE_FEATURE_GUID = "27874239-a79f-4477-919f-f03f7d19a34b";

        public const string TaskAboutToStartQuery = "<Where><And><And><Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq><Geq><FieldRef Name='StartDate'/><Value Type='DateTime'><Today/></Value></Geq></And><Leq><FieldRef Name='StartDate'/><Value Type='DateTime'><Today OffsetDays='{2}'/></Value></Leq></And></Where>";
        public const string TaskNotStartedQuery = "<Where><And><Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq><Lt><FieldRef Name='StartDate'/><Value Type='DateTime'><Today/></Value></Lt></And></Where>";
        public const string TaskDueQuery = "<Where><And><And><Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq><Geq><FieldRef Name='DueDate'/><Value Type='DateTime'><Today/></Value></Geq></And><Leq><FieldRef Name='DueDate'/><Value Type='DateTime'><Today OffsetDays='{2}'/></Value></Leq></And></Where>";
        public const string TaskOverDueQuery = "<Where><And><Neq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Neq><Lt><FieldRef Name='DueDate'/><Value Type='DateTime'><Today/></Value></Lt></And></Where>";

        public const string QueryViewFields = "<FieldRef Name='Title'/><FieldRef Name='AssignedTo'/><FieldRef Name='{0}'/><FieldRef Name='StartDate'/><FieldRef Name='DueDate'/>";
        
        public const string TaskAboutToStartTemplate = "~/_layouts/MFD/TaskStartNotification.htm";
        public const string TaskNotStartedTemplate = "~/_layouts/MFD/TaskNotStartedNotification.htm";
        public const string TaskDueTemplate = "~/_layouts/MFD/TaskDueNotification.htm";
        public const string TaskOverDueTemplate = "~/_layouts/MFD/TaskOverDueNotification.htm";

        

        public static void SendTaskNotification(SPList taskList,string strQuery,string viewFields, string BodyTemplate, string subject, ref List<int> sentEmails)
        {
            SPQuery query = new SPQuery();
            query.ExpandUserField=true;
            query.ViewFields = viewFields;
            
            query.Query = strQuery;
            SPListItemCollection collListItems=taskList.GetItems(query);

            Debug.WriteLine(string.Format("Tasks={0}",collListItems.Count));


            EmailTemplate template = new EmailTemplate();
            template.Subject = subject;
            template.Body = BodyTemplate;


            foreach (SPListItem oListItem in collListItems)
            {
                //try
                //{

                
                var assignedTo = oListItem["AssignedTo"];




                string To=null;


                if (assignedTo is string)
                {
                    SPFieldUser userField = oListItem.Fields.GetField("AssignedTo") as SPFieldUser;
                    SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(assignedTo.ToString());

                    if (fieldValue.User == null)
                    {
                        SPGroup group = taskList.ParentWeb.SiteGroups[fieldValue.LookupValue];
                        To = Notification.GetEmails(group);
                    }
                    else
                        To = GetEmail(fieldValue);
                }
                
                if (assignedTo is SPFieldUserValueCollection)
                    To = GetEmails(assignedTo as SPFieldUserValueCollection,taskList.ParentWeb.SiteGroups);


                
                //var assignedTo = oListItem["AssignedTo"];
                //if (userField != null & assignedTo != null)
                //{


                //    SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(assignedTo.ToString());


                //    SPUser user = fieldValue.User;
                //    if (user != null)
                //    {
                        //string To = user.Email;
                        //if (string.IsNullOrEmpty(To))
                        //{
                        //    Debug.WriteLine(string.Format("Notification not sent! User {0} owns Task: {1} but has no email.", user.Name, oListItem.Title));
                        //}
                        //else
                        if (!string.IsNullOrEmpty(To))
                        {
                            if (sentEmails.Contains(oListItem.ID))
                            {
                                Debug.WriteLine(string.Format("Notification already sent today for task: {0}", oListItem.Title));
                            }
                            else
                            {
                                //add list item to the sentEmails list sowe don't sent multiple notifications for the same item
                                sentEmails.Add(oListItem.ID);

                                TaskNotificationValues values = new TaskNotificationValues(oListItem);


                                Notification.SendEmail(To, template, values);
                                Debug.WriteLine(string.Format("Notification sent for Task: {0}: to {1}", oListItem.Title, To));
                            }
                        }
                    //}
                //}
                //else
                //    Debug.WriteLine(string.Format("Notification not sent! Task: {0} has no owner.", oListItem.Title));
                //}
                //catch (Exception ex)
                //{
                //    Debug.WriteLine(string.Format("Error occured for Task {0} : Error: {1}", oListItem.Title, ex));
                //}
            }


        }

       
        private static string GetEmail(SPFieldUserValue user)
        {
            string ret=null;
            
            

            if (user.User != null)
                ret = user.User.Email;

            return ret;
        }

        private static string GetEmails(SPFieldUserValueCollection users,SPGroupCollection groups)
        {
            string ret = string.Empty ;

            foreach (var user in users)
                if (user.User != null )
                {
                    if (!string.IsNullOrEmpty(user.User.Email))
                        ret += user.User.Email + ";";
                }
                else //it is a sharePoint group
                  ret += Notification.GetEmails(groups[user.LookupValue])+';';

            return ret.TrimEnd(';');
        }

    }
}
